package com.dusk.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dusk.pojo.User;
import com.dusk.service.HouseService;
import com.dusk.service.MessageService;
import com.dusk.service.UserService;

import com.dusk.utils.CommonResult;
import com.dusk.utils.Contants;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;


@RestController
public class PublicController {

    @Resource
    private UserService userService;
    @Resource
    private MessageService messageService;
    @Resource
    private HouseService houseService;

    //保存错误信息
    private static Integer errorStatus = 0;    //处理错误状态

    //登录测试
    @RequestMapping("/login")
    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String userName = request.getParameter("userName");
        String userPassword = request.getParameter("userPassword");
        //比对数据库账号是否正确
        User user = userService.queryUserByAccount(userName);
        if (user != null) { //判断是否拥有此账户
            //再判断密码
            if (user.getUserPassword().equals(userPassword)) {
                request.getSession().setAttribute(Contants.USER_SESSION, user);
                errorStatus = 0;    //改变正确状态
                /*  处理,并将用户信息放入session中 */
                System.out.println("登录成功！");
                response.sendRedirect("pages/all-admin-index.html");
            } else {
                errorStatus = 2;    //密码不对
                response.sendRedirect("pages/index.html");
            }
        } else {
            errorStatus = 1;    //账户错误
            response.sendRedirect("pages/index.html");
        }

    }

    //处理前端登录失败error信息
    @GetMapping("/login/error")
    public String handleLoginError() {
        if (errorStatus == 1) { //账户不对
            CommonResult commonResult = new CommonResult(500, "账户输入错误，请重试");
            String data = JSON.toJSONString(commonResult);
            return data;
        } else if (errorStatus == 2) {  //密码不对
            CommonResult commonResult = new CommonResult(500, "密码不对，请重试");
            String data = JSON.toJSONString(commonResult);
            return data;
        }
        return "";
    }


    //获取用户的基本信息
    @GetMapping("/all-order-manage-edit/message/user")
    public String getUser(HttpServletRequest request, HttpServletResponse response) {
        User user = (User) request.getSession().getAttribute(Contants.USER_SESSION);
        String data = JSON.toJSONStringWithDateFormat(user, "yyyy-MM-dd HH:mm:ss");
        return data;
    }


    //更新用户信息
    //用户增加房屋信息
    @PostMapping(value = "/user-update/user/update", produces = "application/json;charset=UTF-8")
    public String updateUser(@RequestBody String params, HttpServletRequest request) {
        JSONObject outJson = JSONObject.parseObject(params);
        System.out.println(outJson.toString());
        //int id = outJson.getInteger("userId");
        int id = Integer.parseInt(outJson.getString("userId"));
        String userName = outJson.getString("userName");
        String address = outJson.getString("address");
        String sex = outJson.getString("sex");
        String tel = outJson.getString("tel");
        String mail = outJson.getString("mail");
        String userPassword = outJson.getString("userPassword");
        String headImage = outJson.getString("headImage");
        Date updateTime = new Date();
        userService.updateUser(id, userName, address, sex, tel, mail, updateTime, userPassword, headImage);
        //更新后台数据
        User user = userService.queryUserById(id);
        request.getSession().setAttribute(Contants.USER_SESSION, user);
        //System.out.println("房屋增加：" + msg);  //若输出1: 表示增加成功
        String data = JSON.toJSONString("ok");
        return data;
    }


    //增加用户,注册用户
    @PostMapping(value = "/user/add", produces = "application/json;charset=UTF-8")
    public String registerUser(@RequestBody String params) {
        System.out.println(params);
        System.out.println("进入注册功能！");
        JSONObject outJson = JSONObject.parseObject(params);


        String userAccount = outJson.getString("userAccount");
        String mail = outJson.getString("mail");
        String userPassword = outJson.getString("userPassword");
        String userUuid = UUID.randomUUID().toString();
        //默认数据设置
        String userName = "匿名";
        String address = "暂无";
        String sex = "男";
        String tel = "暂无";
        String headImage = "";


        String data = "no"; //返回的数据
        //先判断是否有相同的登录账号，保证唯一性
        User user = userService.queryUserByAccount(userAccount);
        if (user != null) {     //直接不注册，返回错误信息
            return JSON.toJSONString(data);
        }

        // 开始注册
        int res = userService.addUser(new User(userName, userAccount, userPassword, userUuid, sex, tel, mail, address, headImage));


        if (res >= 1) {
            System.out.println("注册成功！");
            data = "yes";
        } else {
            System.out.println("注册失败！");
        }
        //System.out.println("房屋增加：" + msg);  //若输出1: 表示增加成功
        return JSON.toJSONString(data);

    }


    //处理用户注销
    @GetMapping("/user/logout")
    public void logOut(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //取消用户的session的属性
        request.getSession().removeAttribute(Contants.USER_SESSION);
        response.sendRedirect("/pages/index.html");
    }

    //查询房屋，留言，用户总数
    @GetMapping("/user/queryAll")
    public String queryAll() {
        int houses = houseService.queryAllHouseCount();
        int messages = messageService.queryAllMessage();
        int users = userService.queryAllUserCount();
        HashMap<String, Integer> map = new HashMap<>();
        map.put("houseAll", houses);
        map.put("messageAll", messages);
        map.put("userAll", users);
        String data = JSON.toJSONString(map);
        //System.out.println("json数据："+data);
        return data;
    }


    //修改密码
    @PostMapping(value = "/user/password", produces = "application/json;charset=UTF-8")
    public String updateUserPassword(@RequestBody String params) {
        JSONObject outJson = JSONObject.parseObject(params);
        System.out.println(outJson.toString());

        String userAccount = outJson.getString("userAccount");
        String mail = outJson.getString("mail");
        String userPassword = outJson.getString("userPassword");

        String data = "no"; //返回的数据

        // 开始修改密码
        int res = userService.updateUserPassword(userAccount, mail, userPassword);

        if (res >= 1) {
            System.out.println("修改密码成功！");
            data = "yes";
        }
        return JSON.toJSONString(data);
    }

    /**
     * 图片上传
     *
     * @param photo
     * @param request
     * @return
     */
    @RequestMapping(value = "/userHeadUpload", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> uploadPhoto(MultipartFile photo, HttpServletRequest request) {
        Map<String, String> ret = new HashMap<String, String>();
        if (photo == null) {
            ret.put("type", "error");
            ret.put("msg", "选择要上传的文件！");
            return ret;
        }
        if (photo.getSize() > 1024 * 1024 * 10) {
            ret.put("type", "error");
            ret.put("msg", "文件大小不能超过10M！");
            return ret;
        }
        //获取文件后缀
        String suffix = photo.getOriginalFilename().substring(photo.getOriginalFilename().lastIndexOf(".") + 1, photo.getOriginalFilename().length());
        if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) {
            ret.put("type", "error");
            ret.put("msg", "请选择jpg,jpeg,gif,png格式的图片！");
            return ret;
        }
        //获取项目根目录加上图片目录
        String savePath = request.getSession().getServletContext().getRealPath("/") + "/headImage/";
        File savePathFile = new File(savePath);
        if (!savePathFile.exists()) {
            //若不存在该目录，则创建目录
            savePathFile.mkdir();
        }
        //名字由时间加uuid
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String filename = new Date().getTime() + "_" + uuid + "." + suffix;
        try {
            //将文件保存指定目录
            photo.transferTo(new File(savePath + filename));
        } catch (Exception e) {
            ret.put("type", "error");
            ret.put("msg", "保存文件异常！");
            e.printStackTrace();
            return ret;
        }
        ret.put("type", "success");
        ret.put("msg", "上传图片成功！");
        ret.put("filepath", request.getSession().getServletContext().getContextPath() + "/headImage/");
        ret.put("filename", filename);
        System.out.println("图片上传测试成功");
        return ret;
    }
}
